<template>
  <div class="Row_content subcard-create">
    <Form
      inline
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="130">
      <FormItem label="名称:" prop="name">
        <Input v-model="formValidate.name"
          placeholder="请输入"
          :maxlength="30"
          class="Row_content_input">
        </Input>
      </FormItem>
      <FormItem label="副标题:" prop="title">
        <Input v-model="formValidate.title"
          placeholder="请输入"
          :maxlength="60"
          class="Row_content_input">
        </Input>
      </FormItem>
      <FormItem label="价格:" prop="priceCode">
        <Select v-model="formValidate.priceCode"
          style="width:280px; text-align: left">
          <Option v-for="(item, index) in priceList"
            :value="item.configCode"
            :key="index">
            {{ item.configValue }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="局数:" prop="roundCode">
        <Select v-model="formValidate.roundCode"
          style="width:280px; text-align: left">
          <Option v-for="(item, index) in timesList"
            :value="item.configCode"
            :key="index">
            {{ item.configValue }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="门店:"
        style="width: 830px"
        prop="shop">
        <Select v-model="formValidate.shop"
          @on-change="selectShop"
          label-in-value
          filterable
          style="width:280px; text-align: left">
          <Option v-for="item in shopList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem label="销售渠道:" prop="salesChannel">
        <Select v-model="formValidate.salesChannel"
          multiple
          style="width:280px; text-align: left">
          <Option v-for="(item, index) in salesChannels"
            :value="item.number"
            :key="index">
            {{ item.name }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="销售形式:" prop="salesType">
        <Select v-model="formValidate.salesType"
          @on-change="salesTypeChange"
          style="width:280px; text-align: left">
          <Option v-for="(item, index) in salesTypes"
            :value="item.value"
            :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem class="tag-form" label="可选项目:" style="width: 830px" prop="project">
        <div class="tag-container" @click="selectProject">
          <Row type="flex" style="width: 100%">
            <Col span="23">
              <Tag v-for="(item, index) in formValidate.project" :key="index" :name="index" @click.native="selectProject" closable @on-close="deleteProject">{{ item.name }}</Tag>
            </Col>
            <Col span="1" class="tag-flex">
              <Icon type="ios-search" style="font-size: 18px" />
            </Col>
          </Row>
        </div>
      </FormItem>
      <FormItem v-if="formValidate.salesType === 1" label="购买数量限制:" style="width: 830px" prop="buyLimit">
        <Row>
          <Col span="12">
            <Select v-model="formValidate.timeUnitLimit"
              @on-change="timeUnitLimitChange"
              style="text-align: left">
              <Option v-for="(item, index) in timeUnitLimits"
                :value="item.value"
                :key="index">
                {{ item.label }}
              </Option>
            </Select>
          </Col>
          <template v-if="formValidate.timeUnitLimit">
            <Col span="2" style="text-align: center">-</Col>
            <Col span="10">
              <Input @on-keyup="filterSpace"
                v-model="formValidate.buyLimit"
                :maxlength="4">
                <span slot="append">份</span>
              </Input>
            </Col>
          </template>
        </Row>
      </FormItem>
      <FormItem label="每天使用局数限制:" prop="useLimit">
        <Input @on-keyup="filterSpace"
          placeholder="请输入"
          v-model="formValidate.useLimit"
          :maxlength="4"
          class="Row_content_input">
          <span slot="append">局</span>
        </Input>
      </FormItem>
      <FormItem label="有效期:" prop="validType">
        <Select v-model="formValidate.validType"
          @on-change="validTypeChange"
          style="width:280px; text-align: left">
          <Option v-for="(item, index) in timeTypes"
            :value="item.value"
            :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <template v-if="formValidate.validType === 2">
        <FormItem label="时长:" prop="validDays">
          <Input v-model="formValidate.validDays"
            placeholder="请输入"
            :maxlength="6"
            @on-keyup="filterSpace"
            class="Row_content_input">
            <span slot="append">天</span>
          </Input>
        </FormItem>
        <FormItem label="时长:" style="visibility: hidden" prop="validDays">
          <Input class="Row_content_input">
          </Input>
        </FormItem>
      </template>
      <template v-else-if="formValidate.validType === 1">
        <FormItem label="开始时间:" prop="validStart">
          <DatePicker v-model="formValidate.validStart" type="date" placeholder="请选择" style="width: 280px" @on-change="validStartChange" :options="validStartOptions"></DatePicker>
        </FormItem>
        <FormItem label="结束时间:" prop="validEnd">
          <DatePicker v-model="formValidate.validEnd" type="date" placeholder="请选择" style="width: 280px" @on-change="validEndChange" :options="validEndOptions"></DatePicker>
        </FormItem>
      </template>
      <FormItem label="上架时间:" prop="listingTime">
        <DatePicker v-model="formValidate.listingTime" type="date" placeholder="请选择" style="width: 280px" @on-change="listingTimeChange" :options="listingTimeOptions"></DatePicker>
      </FormItem>
      <FormItem label="下架时间:" prop="delistingTime">
        <DatePicker v-model="formValidate.delistingTime" type="date" placeholder="请选择" style="width: 280px" @on-change="delistingTimeChange" :options="delistingTimeOptions"></DatePicker>
      </FormItem>
      <FormItem label="商品详情:" style="width: 830px">
        <div ref="addEditor" class="rich-editor"></div>
      </FormItem>
      <FormItem label="备注:" style="width: 830px">
        <Input v-model="formValidate.remark"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="300"
          placeholder="请描述商品详情"
          class="Row_content_input"></Input>
        <span class="rol_tipsd">
          {{formValidate.remark.length}}/300
        </span>
      </FormItem>
      <FormItem
        label="商品主图:"
        class="set-company-up"
        style="width: 830px">
        <Upload ref="upload"
          :format="['jpg','png']"
          :max-size="500"
          type="drag"
          :show-upload-list="false"
          :action="$config.uploadImg"
          :on-success="uploadSucc"
          :on-exceeded-size="uploadExceeded"
          :on-format-error="uploadFormat"
          style="display: inline-block;width:96px">
          <img :src="formValidate.imgUrl ? formValidate.imgUrl : defaultUrl"
            style="display: inline-block;width:96px;height:96px;vertical-align: top;"
            alt="" />
          <p v-if="formValidate.imgUrl" class="replace_tit" @click.stop="deleteUpload">删除</p>
        </Upload>
        <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;text-align:left">
          <p>支持格式：.jpg、.png</p>
          <p>大小：&lt;500KB</p>
          <p>仅允许上传 1张</p>
        </div>
      </FormItem>
      <FormItem class="form-btn"
        style="margin-top: 5px; width: 830px">
        <Button type="primary"
          @click="handleSubmit"
          class="system-submit-btn">确定</Button>
        <Button class="system-submit-btn"
          @click="handleReset"
          style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
    <select-shop :checkdList="formValidate.project"
      :dataTree="shopProjects"
      :modalShow="modalShow"
      @oncancel="selctshopCancel"
      @selctshop="volumeSet"
      v-if="modalShow">
    </select-shop>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import { getShopList } from '@/api/system/store'
// import { getPriceLists } from '@/api/market/game-ticket/priceTimes.js'
import { getPriceLists } from '@/api/market/game-ticket-old/priceTimes.js'
import { getSalesChannels, getGames, saveSubcard, getSubcardDetail } from '@/api/market/game-ticket/subcardTicketbag.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import SelectShop from '@/view/components/select-project/index.vue'
import editor from '../mixins'
import enumsMixin from '../enums'
import { formatDate } from '@/libs/tools'
export default {
  name: 'market_gameticket_subcard_edit',
  components: { Treeselect, SelectShop },
  mixins: [editor, enumsMixin],
  data () {
    const checkNum = (rule, value, callback) => {
      if (/[a-zA-Z]/.test(value)) {
        callback(new Error('请输入数字'))
      }
      callback()
    }
    return {
      formValidate: {
        name: '',
        title: '',
        priceCode: '',
        roundCode: '',
        shop: null,
        shopName: '',
        salesChannel: '',
        salesType: '',
        project: [],
        timeUnitLimit: 0,
        buyLimit: '1',
        useLimit: '',
        validType: '',
        validStart: '',
        validEnd: '',
        validDays: '',
        listingTime: '',
        delistingTime: '',
        remark: '',
        imgUrl: ''
      },
      priceList: [],
      timesList: [],
      salesTypes: [
        { label: '单独销售', value: 1 },
        { label: '打包销售', value: 2 }
      ],
      timeTypes: [
        { label: '指定时间段', value: 1 },
        { label: '相对时间段', value: 2 }
      ],
      salesChannels: [],
      shopProjects: [],
      modalShow: false,
      validStartOptions: {},
      validEndOptions: {},
      listingTimeOptions: {},
      delistingTimeOptions: {},
      defaultUrl: require('@/assets/images/add.png'),
      ruleValidate: {
        name: { required: true, message: '请填写名称', trigger: 'blur' },
        priceCode: { required: true, message: '请选择价格' },
        roundCode: { required: true, message: '请选择局数' },
        shop: { required: true, message: '请选择门店' },
        salesChannel: { required: true, message: '请选择销售渠道' },
        salesType: { required: true, message: '请选择销售形式' },
        project: { required: true, message: '请选择项目' },
        buyLimit: [{ required: true, message: '请填写购买数量', trigger: 'blur' }, {
          validator: checkNum,
          trigger: 'blur'
        }],
        useLimit: [{ required: true, message: '请填写每天使用局数限制', trigger: 'blur' }, {
          validator: checkNum,
          trigger: 'blur'
        }],
        validType: { required: true, message: '请选择有效期' },
        validStart: { required: true, message: '请选择开始时间' },
        validEnd: { required: true, message: '请选择结束时间' },
        validDays: [{ required: true, message: '请填写时长', trigger: 'blur' }, {
          validator: checkNum,
          trigger: 'blur'
        }],
        listingTime: { required: true, message: '请选择上架时间' },
        delistingTime: { required: true, message: '请选择下架时间' }
      },
      shopList: []
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.id !== to.query.id) {
        vm.id = to.query.id
        vm.getDetail()
      }
    })
  },
  mounted () {
    const query = this.$route.query
    this.id = query.id
    this.trueId = query.trueId
    this.shopId = query.shopId
    this.createEditor(this.$refs.addEditor)
    this.getOrgTree()
    this.getDetail()
    this.getSelects()
  },
  methods: {
    getSelects () {
      this.getPriceOrTimes(1).then(result => {
        this.priceList = result
      })
      this.getPriceOrTimes(2).then(result => {
        this.timesList = result
      })
      getSalesChannels().then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.salesChannels = result.data || []
        }
      })
    },
    filterSpace () {
      this.formValidate.useLimit = this.formValidate.useLimit.replace(/\D/g, '')
      this.formValidate.buyLimit = this.formValidate.buyLimit.replace(/\D/g, '')
      this.formValidate.buyLimit = this.formValidate.buyLimit.replace(/^0/g, '')
      this.formValidate.validDays = this.formValidate.validDays.replace(/^0/g, '')
      this.formValidate.validDays = this.formValidate.validDays.replace(/\D/g, '')
    },
    getPriceOrTimes (type) {
      return new Promise(resolve => {
        getPriceLists({
          merchantId: this.merchantId,
          configType: type
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.data || [])
          }
        })
      })
    },
    resetOneForm (prop) {
      this.$refs['formValidate'].fields.forEach(e => {
        if (e.prop === prop) {
          e.resetField()
        }
      })
    },
    selectShop (data) {
      this.resetOneForm('shop')
      this.formValidate.shop = data.value
      this.formValidate.shopName = data.label
      this.formValidate.project = []
      getGames({
        shopId: data.value
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.formatShopProjects(result.data || [])
        }
      })
    },
    formatShopProjects (projects) {
      this.shopProjects = projects.map(item => {
        item.orgName = item.machineCategoryName
        item.id = item.machineCategoryId
        item.orgType = 0
        item.childList = item.machineInfos.map(childItem => {
          childItem.id = childItem.machineId
          childItem.orgName = childItem.name
          childItem.parentId = item.machineCategoryId
          childItem.orgType = 1
          childItem.childList = []
          return childItem
        })
        return item
      })
    },
    timeUnitLimitChange () {
      this.resetOneForm('buyLimit')
      if (this.formValidate.timeUnitLimit) {
        this.formValidate.buyLimit = ''
      } else {
        this.formValidate.buyLimit = '1'
      }
    },
    salesTypeChange (val) {
      this.formValidate.timeUnitLimit = 0
      this.formValidate.buyLimit = '1'
    },
    validTypeChange () {
      this.resetOneForm('validStart')
      this.resetOneForm('validEnd')
      this.resetOneForm('validDays')
      this.formValidate.validStart = ''
      this.formValidate.validEnd = ''
      this.formValidate.validDays = ''
    },
    getDetail () {
      if (this.id) {
        getSubcardDetail({
          shopId: this.shopId,
          gameCouponCode: this.id
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            const data = result.data || {}
            this.selectShop({
              value: data.shopId,
              label: data.shopName
            })
            this.formValidate = {
              name: data.name,
              title: data.title,
              priceCode: data.priceCode,
              roundCode: data.roundCode,
              round: data.round.configValue,
              shop: data.shopId,
              shopName: data.shopName,
              salesChannel: data.salesChannelNumber,
              salesType: data.salesType,
              project: data.machineDetail.map(item => {
                return {
                  ...item,
                  id: item.machineId,
                  orgName: item.machineName,
                  name: item.machineName,
                  orgType: 1,
                  childList: []
                }
              }),
              timeUnitLimit: data.timeUnitLimit,
              useLimit: data.useLimit + '',
              buyLimit: data.buyLimit ? data.buyLimit + '' : '1',
              validType: data.validType,
              validStart: data.validStart || '',
              validEnd: data.validEnd || '',
              validDays: data.validDays ? data.validDays + '' : '',
              listingTime: data.listingTime,
              delistingTime: data.delistingTime,
              remark: data.remark,
              imgUrl: data.imgUrl
            }
            this.$editorContent = data.detail || ''
            this.$editor.txt.html(data.detail || '')
            if (data.validType === 1) {
              this.validEndOptions = {
                disabledDate (date) {
                  return date.valueOf() < new Date(data.validStart).getTime()
                }
              }
              this.validEndChange(data.validEnd)
            }
            this.delistingTimeOptions = {
              disabledDate (date) {
                return date.valueOf() < new Date(data.listingTime).getTime()
              }
            }
            this.delistingTimeChange(data.delistingTime)
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      }
    },
    selectProject () {
      if (!this.shopProjects.length) {
        this.$Message.error('该门店没有项目')
      } else {
        this.modalShow = true
      }
    },
    selctshopCancel () {
      this.modalShow = false
    },
    volumeSet (val) {
      this.modalShow = false
      this.resetOneForm('project')
      this.formValidate.project = val
    },
    deleteProject (event, index) {
      this.formValidate.project.splice(index, 1)
    },
    getOrgTree () {
      getShopList({
        permissionCode: 'moms:market:viewroundgamecouponlist',
        merchantId: this.merchantId,
        offset: 0,
        limit: 9999
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.shopList = (result.data || []).map(item => {
            return {
              label: item.shopName,
              value: item.shopId
            }
          })
        }
      })
    },
    validStartChange (time) {
      this.validEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time).getTime() - 24 * 60 * 60 * 1000
        }
      }
    },
    validEndChange (time) {
      this.validStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    listingTimeChange (time) {
      this.delistingTimeOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time).getTime() - 24 * 60 * 60 * 1000
        }
      }
    },
    delistingTimeChange (time) {
      this.listingTimeOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    uploadSucc (response) {
      this.formValidate.imgUrl = response.full_img_url
    },
    uploadExceeded () {
      this.$Message.error('文件大小不能超过500kb')
    },
    uploadFormat () {
      this.$Message.error('请上传jpg/png文件')
    },
    deleteUpload () {
      this.formValidate.imgUrl = ''
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        const formValidate = this.formValidate
        if (formValidate.validEnd && formValidate.validEnd < formValidate.delistingTime) {
          this.$Message.error('结束时间必须晚于下架时间')
        } else if (val) {
          const params = {
            merchantId: this.merchantId,
            shopId: formValidate.shop,
            shopName: formValidate.shopName,
            name: formValidate.name,
            title: formValidate.title,
            priceCode: formValidate.priceCode,
            roundCode: formValidate.roundCode,
            salesChannel: formValidate.salesChannel.reduce((prev, next) => prev + next),
            salesType: formValidate.salesType,
            type: 1,
            validType: formValidate.validType,
            useLimit: +formValidate.useLimit,
            imgUrl: formValidate.imgUrl,
            detail: this.$editor.txt.html(),
            remark: formValidate.remark,
            listingTime: formatDate(formValidate.listingTime, 'yyyy-MM-dd hh:mm:ss'),
            delistingTime: formatDate(formValidate.delistingTime, 'yyyy-MM-dd hh:mm:ss'),
            machineDetail: formValidate.project.map(item => {
              return {
                machineId: item.machineId,
                machineName: item.name
              }
            }),
            operator: this.userName,
            operatorId: this.userId
          }
          if (formValidate.salesType === 1) {
            params.timeUnitLimit = formValidate.timeUnitLimit
          } else {
            params.timeUnitLimit = 0
          }
          if (formValidate.timeUnitLimit) {
            params.buyLimit = +formValidate.buyLimit
          }
          if (formValidate.validType === 1) {
            params.validStart = formatDate(formValidate.validStart, 'yyyy-MM-dd hh:mm:ss')
            params.validEnd = formatDate(formValidate.validEnd, 'yyyy-MM-dd hh:mm:ss')
          } else {
            params.validDays = +formValidate.validDays
          }
          if (this.id) {
            params.id = this.trueId
            params.gameCouponCode = this.id
          }
          saveSubcard(params).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success(this.id ? '编辑成功！' : '新增成功！')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_gameticket_subcard'
        })
      })
    }
  }
}
</script>

<style lang="less">
.subcard-create {
  width: 890px;
  .ivu-form {
    text-align: center
  }
  .ivu-upload {
    width: 96px;
    height: 96px;
    position: relative;
    border: 0;
    &.ivu-upload-drag {
      border: 1px solid #dcdee2
    }
    .replace_tit {
      position: absolute;
      bottom: 0;
      width: 96px;
      opacity: 0.6;
      background: #ED4014;
      height: 24px;
      text-align: center;
      line-height: 24px;
      font-size: 12px;
      color: #ffffff;
      display: none;
    }
    &:hover .replace_tit {
      display: block;
    }
  }
  .set-company-up .ivu-form-item-content {
    display: flex;
  }
  .set-company-up .ivu-form-item-label::before {
    display: none;
  }
  .rich-editor {
    width: 700px;
    text-align: left;
    .w-e-toolbar {
      flex-wrap: wrap
    }
  }
  .tag-form {
    .ivu-form-item-content {
      width: 700px
    }
    .tag-container {
      display: flex;
      flex-wrap: wrap;
      min-height: 32px;
      padding: 4px 7px;
      min-width: 280px;
      border: 1px solid #dcdee2;
      border-radius: 4px;
      cursor: pointer;
      text-align: left;
    }
    .tag-flex {
      display: flex;
      justify-content: center;
      align-items: center
    }
  }
  .vue-treeselect__menu {
    max-height: 200px !important
  }
}
</style>
